# -*- coding: utf-8 -*-
# Author: xiantingDeng
# File: generatecase_ls.py
# Time: 19:18

import os
import time
import sys
import os

sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(""))))
from common.tools.convert_ls import convert_str_to_hump
from common.utils.file_util import get_case_dir, create_file, mkdir
from common.utils.read_util import OperationYaml


def generate_case(feature, api_name, env):
    case = f"""
# -*- coding: utf-8 -*-
# Author: xiantingDeng
# Time: {time.strftime("'%Y-%m-%d_%H_%M", time.localtime())}



import allure
import pytest

from common.tools.validate_ls import AssertionIs
from common.utils.request_util import RestClient
from common.tools.transmit_data_ls import GeneratingCaseData

@allure.feature("{{module}}")
@allure.story("{{describe}}")
@allure.title("{{validation}}")
class {convert_str_to_hump(api_name)}:
    @allure.severity(allure.severity_level.NORMAL)
    @pytest.mark.parametrize(
        "ip,method,url,data,json,params,headers,files,cookies,timeout,code,message,respon,module,describe,validation",
        GeneratingCaseData("{feature}", "{api_name}","{env}").get_yaml_case())
    def {api_name}(self,log, ip, method, url, data, json, params, headers, files, cookies, timeout, code, message,
                            respon, module, describe, validation):
        with allure.step("第一步：发送请求，获取响应实体"):
            response = RestClient(log, ip).requests(method=method,
                                                    url=url,
                                                    data=data,
                                                    json=json,
                                                    params=params,
                                                    headers=headers,
                                                    files=files,
                                                    cookies=cookies,
                                                    timeout=timeout)
            result = response.json()
    
            allure.attach(response.url, "请求：", allure.attachment_type.TEXT)
            allure.attach(response.text, "响应：", allure.attachment_type.TEXT)
    
        with allure.step("第二部：运行断言器，开始进行断言"):
            try:
                if AssertionIs(log).assert_code(response.status_code, code):
                    if AssertionIs(log).assert_msg(result, message, respon):
                        log.info("接口测试通过，开始进行下一个接口")
                else:
                    pytest.fail("接口响应码与预期不一致，接口失败", False)
            except Exception as e:
                raise e
            finally:
                log.info("-" * 100)
"""

    # 创建模块目录
    feature_path = get_case_dir(feature)
    mkdir(feature_path)

    # 创建用例文件
    test_path = os.path.join(feature_path, "{}.py".format(api_name.split(".")[0]))
    create_file(test_path, case)

    init = os.path.join(feature_path, "__init__.py")
    if not os.path.isfile(init):  # 无文件时创建
        fd = open(init, mode="w", encoding="utf-8")
        fd.close()
        if os.path.exists(init):
            return True
        else:
            return False


def gen_all_case():
    """ 生成 configs/all_api.yml 内所有 case
    """
    all_api = OperationYaml("all_api.yml").get_own_yaml()
    for k, v in all_api.items():
        if v:  # 判断 feature 不为空
            for api in v:
                generate_case(k, api[0], api[1])



if __name__ == '__main__':
    # generate_case("user_test","nishuone")
    print(gen_all_case())
